package main.service;

import java.io.File;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;

import main.dao.UserDAO;
import main.entity.UserVO;
import main.utils.StrUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Service
public class IOService {
	
	@Autowired
	private UserDAO userDAO;
	
	public ArrayList<String> upload(@RequestParam("myFile") MultipartFile[] files, HttpServletRequest request) {
		
		ArrayList<String>upResults = new ArrayList<String>();
		for (MultipartFile multipartFile : files) {
			upResults.add( handleUploadFile(multipartFile, request) );
		}
//		request.setAttribute("upResults", upResults);
//		return "/headImg";
		return upResults;
	}
	
	public Boolean upHdImg(@RequestParam("myFile") MultipartFile upFile, Integer UID, HttpServletRequest request) {
		
		Boolean upResult = new Boolean(false);
		String hdImgPath = handleUploadFile(upFile, request);
			if (hdImgPath!=null ){
				UserVO userVO = userDAO.getByID(UserVO.class, UID);
				userVO.setHdImgPath(hdImgPath);
				upResult = userDAO.update(userVO);
//				upResult= PK==null?false:true;
			}
		return upResult;
	}
	
	public static String handleUploadFile(MultipartFile file, HttpServletRequest request){
//		Boolean isOK = false;
		String hdImgPath = null;
		if (!file.isEmpty() && file!=null) {
			// 获取WebRoot下upload文件上传路径的物理地址。
			String file_dir = request.getSession().getServletContext()
					.getRealPath("/upload");
			// 获取需要上传文件名
			String file_name = file.getOriginalFilename();
			String addName = StrUtil.getRandomFileName();
			// 拼接出上传文件的完整路径
			String file_dir_name = file_dir + File.separator  + addName +"_"+ file_name;
			File destFile = new File(file_dir_name);
			try {
				// 通过MultipartFile组件实现上传
				file.transferTo(destFile);
				hdImgPath = file_dir_name;
//				request.setAttribute("message", "文件上传成功");
//				isOK = true;
			} catch (Exception e) {
				e.printStackTrace();
//				request.setAttribute("message", "文件上传失败");
			}
		}
		return hdImgPath;		
	}
}
